#!/usr/bin/python
# -*- coding: utf-8 -*-
# coding: utf-8

import smtplib
from smtplib import SMTPRecipientsRefused
from email.MIMEText import MIMEText
import MySQLdb
import sys
import time

serverSMTP="localhost"
serverMySQL="localhost"
userMySQL="admin"
passWordMySQL=""

basesToProcess=["comexpert"]

server=smtplib.SMTP(serverSMTP);

db=MySQLdb.connect(serverMySQL, userMySQL, passWordMySQL)
c=db.cursor()
c.execute("SET NAMES 'utf8'")
c.execute("SET CHARACTER SET utf8")

for base in basesToProcess:
	c.execute("USE %s" % (base))

	sql="select c.nom, ec.description, u.mail "
	sql+="from echeancesClient as ec "
	sql+="inner join client as c on c.code=ec.client "
	sql+="inner join utilisateur as u on u.code=ec.destinataire "
	sql+="where dateEcheance <= DATE_ADD(CURDATE(), INTERVAL 1 DAY) AND mailAEcheance='OUI'"

	c.execute(sql)
	rows=c.fetchall()

	for row in rows:
		msg=MIMEText("<html><body><h1>"+row[0]+"</h1><hr>"+row[1]+"<br></body></html>", _subtype="html", _charset="utf-8")
		msg['From']=u"Echéance client <lebail.corentin@neuf.fr>"
		msg['Reply-to']="lebail.corentin@neuf.fr"
		msg['Subject']=u"*** Echéance client ***"
		msg['To']=row[2]

		server.sendmail(msg['From'], msg['To'], msg.as_string())
		
c.close()

server.quit()
